//
//  MainTodayGroup.m
//  cherryproduct
//
//  Created by umessage on 14-8-6.
//  Copyright (c) 2014年 cherry. All rights reserved.
//

#import "MainTodayGroup.h"
#import "UIImageView+AFNetworking.h"
#import "MainTodayGroupCellelement.h"

#define TABLEVIEWCELLHEIGHT 145

@implementation MainTodayGroup

@synthesize delegate;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
      
    }
    return self;
}

-(void)starttimer //倒计时
{
    BOOL isstoptimer = YES;
    int num = 0;
    if ([[dicdata objectForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
        num = 1;
    } else {
        num = [[dicdata objectForKey:@"data"] count];
    }
    for(int i = 0 ; i < num ; i++)
    {
        NSIndexPath * indexpath = [NSIndexPath indexPathForRow:i inSection:0];
        UITableViewCell * cell = [tableview cellForRowAtIndexPath:indexpath];
        MainTodayGroupCellelement * cellelement = (MainTodayGroupCellelement*)[cell viewWithTag:1002];
        
        UILabel * labeltime = (UILabel*)[cellelement viewWithTag:106]; //团购时间
        NSDateFormatter * formaater = [[NSDateFormatter alloc] init];
        [formaater setDateFormat:@"HH:mm:ss"];
        
        if([[dicdata objectForKey:@"data"] isKindOfClass:[NSDictionary class]])
        {
            long long timeover = [[[dicdata objectForKey:@"data"] objectForKey:@"end_time"] longLongValue] - [[NSDate date] timeIntervalSince1970];
            
            NSTimeInterval end_time = [[[dicdata objectForKey:@"data"] objectForKey:@"end_time"] longLongValue];
            NSDate * date_end_time = [NSDate dateWithTimeIntervalSince1970:end_time];
            NSDate * date_today_time = [NSDate date];
            
            NSTimeInterval time = [date_end_time timeIntervalSinceDate:date_today_time];
            int days=(time)/(3600*24);
            int doutime = time - days*(3600*24);
            int hours=doutime/3600;
            int mont = (doutime%3600)/60;
            int sec = (doutime%3600)%60;
            
            NSString * dateContent = [[NSString alloc] initWithFormat:@"%d:%d:%d", days*24+hours, mont, sec];
            
            if(timeover>0)
            {
                isstoptimer = NO;
                labeltime.text = dateContent;//[formaater stringFromDate:[[NSDate alloc] initWithTimeIntervalSince1970:timeover]];
            } else {
                labeltime.text = @"已过期";
            }
        } else {
            //判断是否开团
            {
                NSString * str_start_time_formate = [[[dicdata objectForKey:@"data"] objectAtIndex:i] objectForKey:@"start_time_formate"];
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
                NSDate * destDate= [dateFormatter dateFromString:str_start_time_formate];
                
                NSDate * date_now = [NSDate date];
                
                if ([date_now compare:destDate] == NSOrderedAscending) {
                    {
                        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                        [dateFormatter setDateFormat:@"HH:mm开始"];
                        NSString * destDateString = [dateFormatter stringFromDate:destDate];
                        labeltime.text=destDateString;
                    }
                    
                    continue;
                }
            }
            
            
            long long timeover = [[[[dicdata objectForKey:@"data"] objectAtIndex:i] objectForKey:@"end_time"] longLongValue] - [[NSDate date] timeIntervalSince1970];
            
//            NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
//            [formatter setDateStyle:NSDateFormatterMediumStyle];
//            [formatter setTimeStyle:NSDateFormatterShortStyle];
//            [formatter setDateFormat:@"ddHHMMss"];//yyyyMM
            
            
            NSTimeInterval end_time = [[[[dicdata objectForKey:@"data"] objectAtIndex:i] objectForKey:@"end_time"] longLongValue];
            NSDate * date_end_time = [NSDate dateWithTimeIntervalSince1970:end_time];
             
//            NSString *end = @"2014-9-16 18:18:12";
//            NSDateFormatter *f = [[NSDateFormatter alloc] init];
//            [f setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//            NSDate * date_end_time = [f dateFromString:end];
            
            NSDate * date_today_time = [NSDate date];
            
            NSTimeInterval time = [date_end_time timeIntervalSinceDate:date_today_time];
            //NSTimeInterval time = end_time - [[NSDate date] timeIntervalSince1970];
            int days=(time)/(3600*24);
            int doutime = time - days*(3600*24);
            int hours=doutime/3600;
            int mont = (doutime%3600)/60;
            int sec = (doutime%3600)%60;
            
            NSString * dateContent = [[NSString alloc] initWithFormat:@"%d:%d:%d", days*24+hours, mont, sec];
            if (sec < 10) {
                dateContent = [[NSString alloc] initWithFormat:@"%d:%d:0%d", days*24+hours, mont, sec];
            }
            
            if (timeover > 0)
            {
                isstoptimer = NO;
                labeltime.text = dateContent;//[formaater stringFromDate:[[NSDate alloc] initWithTimeIntervalSince1970:timeover]];
            }
            else
            {
                labeltime.text = @"已过期";
            }
        }
    }
    if(isstoptimer)
    {
        if([timer isValid])
        {
            [timer invalidate];
        }
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if([[dicdata objectForKey:@"data"] isKindOfClass:[NSDictionary class]])
    {
        return 1;
    }
    else
    {
        return [[dicdata objectForKey:@"data"] count];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return TABLEVIEWCELLHEIGHT;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.delegate MainTodayGroupDownIndex:indexPath.row];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* stringmainviewtoday = @"todaymain";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:stringmainviewtoday];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:stringmainviewtoday];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UIImageView*imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0,DEVICE_BOUNDS_WIDTH , TABLEVIEWCELLHEIGHT)];
        imageview.tag = 1001;
        imageview.contentMode=UIViewContentModeScaleAspectFit;
        [cell addSubview:imageview]; //背景图片
        
        MainTodayGroupCellelement* cellelement = [[MainTodayGroupCellelement alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        cellelement.tag = 1002;
        [cell addSubview:cellelement];//圆圈的元素
        
    }
    if([[dicdata objectForKey:@"data"] isKindOfClass:[NSDictionary class]])
    {
        NSDictionary* dic = [dicdata objectForKey:@"data"];
        NSMutableString* jpgstring = [[NSMutableString alloc] init];
        [jpgstring appendString:JPG];
        [jpgstring appendString:[dic objectForKey:@"photo"]];
        [(UIImageView*)[cell viewWithTag:1001] setImageWithURL:[NSURL URLWithString:jpgstring]placeholderImage:[UIImage imageNamed:@"todaygrouploading"]];
        MainTodayGroupCellelement* today = (MainTodayGroupCellelement*)[cell viewWithTag:1002];
        int flag = indexPath.row%2;
        [today getusedata:dic leftright:flag];

    }
    else
    {
        NSArray* array = [dicdata objectForKey:@"data"];
        NSMutableString* jpgstring = [[NSMutableString alloc] init];
        [jpgstring appendString:JPG];
        [jpgstring appendString:[[array objectAtIndex:indexPath.row] objectForKey:@"photo"]];
        [(UIImageView*)[cell viewWithTag:1001] setImageWithURL:[NSURL URLWithString:jpgstring] placeholderImage:[UIImage imageNamed:@"todaygrouploading"]];
        MainTodayGroupCellelement* today = (MainTodayGroupCellelement*)[cell viewWithTag:1002];
        int flag = indexPath.row%2;
        [today getusedata:[array objectAtIndex:indexPath.row] leftright:flag];
    }
    return cell;
    
}
-(void)dealloc
{
    if([timer isValid])
    {
        [timer invalidate];
    }
}

-(void)getusedata:(NSDictionary*)dic
{
    if(dicdata)
    {
        [dicdata removeAllObjects];
    }
    dicdata = [[NSMutableDictionary alloc] initWithDictionary:dic copyItems:YES];
    
    if (tableview == nil) {
        tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) style:UITableViewStylePlain];
        tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableview.delegate = self;
        tableview.dataSource = self;
        [self addSubview:tableview];
    }
    [tableview reloadData];
    
    if (timer ) {
        if ([timer isValid]) {
            [timer invalidate];
        }
    }
    
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                             target:self
                                           selector:@selector(starttimer)
                                           userInfo:nil
                                            repeats:YES];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end



















